import java.io.IOException;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

public class CommonServlet extends HttpServlet {
	private static final long serialVersionUID = 1L;
	
	HttpSession session;
	
	PizzaBean pb;
	NameBean nb;
	MoneyBean mb;
	
	protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		// Sessie ophalen
		session = request.getSession(false);
		if (session != null)
		{
			//System.out.println("Session found: id = "+session.getId());
		}
		
		if(session == null) {
			
			session = request.getSession(true);
			//System.out.println("session not found: new session id = "+session.getId());
			
		}
		// Beans uit sessie ophalen (mits aanwezig).
		if(session.getAttribute("pb") != null) {
			pb = (PizzaBean) session.getAttribute("pb");
			request.setAttribute("pb", pb);
		} else {
			pb = new PizzaBean();
			session.setAttribute("pb", pb);
			request.setAttribute("pb", pb);
		}
		if(session.getAttribute("nb") != null) {
			nb = (NameBean) session.getAttribute("nb");
			request.setAttribute("nb", nb);
		} else {
			
			nb = new NameBean();
			session.setAttribute("nb", nb);
			request.setAttribute("nb", nb);
		}
		if(session.getAttribute("mb") != null) {
			mb = (MoneyBean) session.getAttribute("mb");
			request.setAttribute("mb", mb);
		} else {
			mb = new MoneyBean();
			session.setAttribute("mb", mb);
			request.setAttribute("mb", mb);
		}		
		
		super.service(request, response);
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
		System.out.println("AbstractServlet.doGet()");
	}
	
	public void doPost(HttpServletRequest request, HttpServletResponse response, CommonBean ab) throws ServletException, IOException {
	  System.out.println("AbstractServlet.doPost()");
	}
	
	public boolean checkPreviousPage(HttpServletResponse response, String[] names) {
		boolean isValid = false;
		
		for(String name : names) {
			if(session.getAttribute("previous").equals(name)) {
				isValid = true;
			} else {
				 
			}
		}
		
		if(!isValid) {
			try {
				System.out.println("OK");
				response.sendRedirect("pizza");
			} catch (IOException e) {
				System.out.println("ERRRRRRRRRRR:"+e.getMessage());
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
		}
		return isValid;
	}

}
